//
//  foodHomeViewController.m
//  孕妙
//
//  Created by 是源科技 on 16/6/27.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "foodHomeViewController.h"
#import "foodPlanView.h"
#import "foodJiluViewController.h"
#import "foodJieGouView.h"
#import "planFoodViewController.h"
#import "foodYuanzeViewController.h"
#import "foodExchangeViewController.h"
#import "foodPlan.h"
#import "shanshiFenxiViewController.h"
#import "YBHealthCalendar.h"
#import "YBHealthControllerNew.h"


@interface foodHomeViewController ()
@property (nonatomic,strong)UIScrollView *displayScrollView;
@property (nonatomic,weak)UILabel *goldLabel;
@property (nonatomic,assign)CGFloat secY; //第二个界面的位置变量

@property (nonatomic,weak)UILabel *firstLabel; //今天还可以摄入

@property (nonatomic,weak)UIView *tnbBackgroundView;
@property (nonatomic,weak)UIView *tnbView;

@property (nonatomic,weak)UIView *view2;
@property (nonatomic,weak)UIView *view1;

@property (nonatomic,weak)UILabel *timeLabel;

//糖尿病按钮
@property (nonatomic,weak)UIButton *noButton;
@property (nonatomic,weak)UIButton *haveButton;
@property (nonatomic,assign)int tnbType;

@property (nonatomic,strong)NSArray *titleArray;

@property (nonatomic,strong)NSMutableArray *breakFastArray;
@property (nonatomic,strong)NSMutableArray *breakFastPlusArray;
@property (nonatomic,strong)NSMutableArray *lunchFastArray;
@property (nonatomic,strong)NSMutableArray *lunchFastPlusArray;
@property (nonatomic,strong)NSMutableArray *dinnerFastArray;
@property (nonatomic,strong)NSMutableArray *dinnerFastPlusArray;

//膳食结构数组
@property (nonatomic,strong)NSMutableArray *totalMutableArray;
@property (nonatomic,strong)NSMutableArray *alreadyMutableArray;

@property (nonatomic,strong)NSMutableArray *foodMutableArrayM;

@property (nonatomic, strong) YBHealthCalendar *healthCalendar;//日历
/**
 日历是否正在动画
 */
@property (assign, getter = isAnimating) BOOL animating;
/**
 * 灰色背景View
 */
@property (nonatomic, weak) UIView *shadowView;
/**
 * 日历view
 */
@property (nonatomic, strong) UIView *calendarView;
/**
 当前日历上显示数据的日期，界面上当前显示的日期
 */
@property (nonatomic, strong) NSDate *calendarDisplayDate;

@property (nonatomic,copy)NSString *selectDateString;
@property (nonatomic,copy)NSString *currentDateString;

@property (nonatomic,assign)BOOL riliFlag;




@end

@implementation foodHomeViewController

-(NSArray *)titleArray
{
    if(!_titleArray)
    {
        _titleArray = @[@"谷薯",@"蔬菜",@"水果",@"大豆",@"奶类",@"肉蛋",@"硬果",@"油脂"];
    }
    return _titleArray;
}

-(UIView *)displayView
{
    if(!_displayScrollView)
    {
        _displayScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
        [self.view addSubview:_displayScrollView];
    }
    return _displayScrollView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"膳食管理";
    self.view.backgroundColor = YMColor(245, 245, 245);
    self.breakFastArray = [NSMutableArray array];
    self.breakFastPlusArray = [NSMutableArray array];
    self.lunchFastArray = [NSMutableArray array];
    self.lunchFastPlusArray = [NSMutableArray array];
    self.dinnerFastArray = [NSMutableArray array];
    self.dinnerFastPlusArray = [NSMutableArray array];
    self.totalMutableArray = [NSMutableArray array];
    self.alreadyMutableArray = [NSMutableArray array];
    self.tnbType = 0;
  
    //设置右按钮
    UIButton *dateButton = [UIButton buttonWithType:UIButtonTypeCustom];
    dateButton.frame =  CGRectMake(0, 0, 30.0f, 30.0f);
    [dateButton setImage:[UIImage imageNamed:@"calendar_icon"] forState:UIControlStateNormal];
    UIBarButtonItem *dateButtonItem = [[UIBarButtonItem alloc] initWithCustomView:dateButton];
    self.navigationItem.rightBarButtonItem = dateButtonItem;
    [dateButton addTarget:self action:@selector(clickCalenderBtn) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.foodMutableArrayM = [NSMutableArray array];

//    [self getFoodInformationFromServices];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    YMLog(@"系统时间   %@",[self getSystemTime]);
    self.selectDateString = [self getSystemTime];
    self.currentDateString= [self getSystemTime];
}

-(void)riliLayout
{
    UIView *shadowView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.shadowView = shadowView;
    shadowView.backgroundColor = [UIColor clearColor];
//    shadowView.alpha = 0.3;
    [self.view addSubview:shadowView];
    
    NSDateFormatter*df = [[NSDateFormatter alloc]init];//格式化
    [df setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [df dateFromString:self.selectDateString];
    
    YBHealthCalendar *healthCalendar = [[YBHealthCalendar alloc] initWithCurrentDate:date];
    self.healthCalendar = healthCalendar;
    CGRect frame = healthCalendar.frame;
    frame.origin.y = 64;
    healthCalendar.frame = frame;
    [self.view addSubview:healthCalendar];
    
    // 监听date属性变化
    [self.healthCalendar addObserver:self forKeyPath:@"date" options:0 context:nil];
    [self observeValueForKeyPath:nil ofObject:nil change:nil context:nil];
    
    self.shadowView.hidden = YES;
    self.healthCalendar.hidden = YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.shadowView.hidden = YES;
    self.riliFlag = NO;
    self.healthCalendar.hidden = YES;
}

#pragma mark 点击日历按钮
- (void)clickCalenderBtn
{
    if(self.riliFlag)
    {
        self.shadowView.hidden = YES;
        self.healthCalendar.hidden = YES;
        self.riliFlag = NO;
    }
    else
    {
        self.shadowView.hidden = NO;
        self.healthCalendar.hidden = NO;
        self.riliFlag = YES;
    }
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"date"]) {
        [UIView animateWithDuration:1.0 animations:^{
           
        } completion:^(BOOL finished) {
            self.healthCalendar.hidden = YES;
            self.shadowView.hidden = YES;
            self.riliFlag = NO;
        }];
        
        // 设置日期切换
        NSCalendar *calendar = [NSCalendar currentCalendar];
        int unit = NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear | NSCalendarUnitWeekday;
        
        // 1.获得当前时间的年月日
        NSDateComponents *nowCmps = [calendar components:unit fromDate:self.healthCalendar.date];
        self.calendarDisplayDate = self.healthCalendar.date;
        self.selectDateString =  [NSString stringWithFormat:@"%ld-%02ld-%02ld", (long)nowCmps.year, (long)nowCmps.month, (long)nowCmps.day];
        
        int selectDateInt = [self stringFormationToInt:self.selectDateString];
        int currentDateInt = [self stringFormationToInt:self.currentDateString];
        
         YMLog(@"selectDate = %d   currentDate = %d",selectDateInt,currentDateInt);
        
        // 界面上当前显示的日期
        if (selectDateInt > currentDateInt) //选择的日期大
        {
            [MBProgressHUD showError:@"日期选择错误!!"];
            self.selectDateString = self.currentDateString;
             NSDateFormatter*df = [[NSDateFormatter alloc]init];//格式化
             [df setDateFormat:@"yyyy-MM-dd"];
             NSDate *date = [df dateFromString:self.selectDateString];
            [self.healthCalendar setDate:date];
            
            
        }
        else
        {
            self.timeLabel.text = [NSString stringWithFormat:@"您在%ld-%02ld-%02ld的膳食摄入量",(long)nowCmps.year, (long)nowCmps.month, (long)nowCmps.day];
        }
    }
}

/**string 转 int*/
-(int)stringFormationToInt:(NSString *)str
{
    int dateInt = 0;
    NSString *newStr = nil;
    NSRange yearRang = {0,4};
    NSRange  monthRang = {5,2};
    NSRange dayRang = {8,2};
    newStr = [str substringWithRange:yearRang];
    newStr = [newStr stringByAppendingString:[str substringWithRange:monthRang]];
    newStr = [newStr stringByAppendingString:[str substringWithRange:dayRang]];
    dateInt = [newStr intValue];
    return dateInt;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    for (UIView *view in self.view2.subviews) {
        [view removeFromSuperview];
    }
 
    self.foodMutableArrayM = [NSMutableArray array];
    self.breakFastArray = [NSMutableArray array];
    self.breakFastPlusArray = [NSMutableArray array];
    self.lunchFastArray = [NSMutableArray array];
    self.lunchFastPlusArray = [NSMutableArray array];
    self.dinnerFastArray = [NSMutableArray array];
    self.dinnerFastPlusArray = [NSMutableArray array];
    
    self.totalMutableArray = [NSMutableArray array];
    self.alreadyMutableArray = [NSMutableArray array];
    //从服务器上获取膳食结构内容
    [self getFoodInformationFromServices];
    

    YMLog(@"self.selectDateString = %@",self.selectDateString);
    

}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if([passValue passValue].exchangeFoodFlag == YES)
    {
        [UIView animateWithDuration:0.5 animations:^{
            self.displayScrollView.contentOffset = CGPointMake(0, kDeviceHeight);
        }];

    }
     [self riliLayout];//日历布局
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    for (UIView *view in self.view1.subviews) {
        [view removeFromSuperview];
    }
    [passValue passValue].exchangeFoodFlag = NO;
    
    [self.healthCalendar removeObserver:self forKeyPath:@"date"];
    [self.healthCalendar removeFromSuperview];
    self.healthCalendar = nil;
    [self.shadowView removeFromSuperview];
    self.shadowView = nil;
    self.riliFlag = NO;

}

//糖尿病弹窗布局
-(void)tangniaobingLayout
{
    UIView *backGroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kDeviceWidth, kDeviceHeight)];
    backGroundView.backgroundColor = [UIColor blackColor];
    backGroundView.alpha = 0.5;
    self.tnbBackgroundView = backGroundView;
    [self.view addSubview:backGroundView];
    
    UIButton *closeBtn = [[UIButton alloc]initWithFrame:backGroundView.bounds];
    [closeBtn addTarget:self action:@selector(clickCloseButton:) forControlEvents:UIControlEventTouchUpInside];
    [backGroundView addSubview:closeBtn];
    
    UIView *tnbView = [[UIView alloc]initWithFrame:CGRectMake(kDeviceWidth / 16.0, kDeviceHeight / 3.25, kDeviceWidth / 8.0 * 7, kDeviceWidth / 8.0 * 7 / 1.11)];
    tnbView.layer.borderColor = [YMColor(252, 160, 207)CGColor];
    tnbView.layer.borderWidth = 0.5;
    tnbView.layer.cornerRadius = 18.0f;
    tnbView.backgroundColor = [UIColor whiteColor];
    self.tnbView = tnbView;
    [self.view addSubview:tnbView];
    
    self.tnbView.hidden = YES;
    self.tnbBackgroundView.hidden = YES;
    
    [self addTangNiaoBingNeiRongToView:self.tnbView];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getTangNiaoBingInformationfromServices];
    });
}

/**往糖尿病view上添加内容*/
-(void)addTangNiaoBingNeiRongToView:(UIView *)view
{
    CGFloat w = view.frame.size.width;
    CGFloat h = view.frame.size.height;
    
    CGFloat viewH = (h - 20) / 3.0;
    for(int i = 0;i < 3;i ++)
    {
        UIView *littleView = [[UIView alloc]initWithFrame:CGRectMake(0, viewH * i, w, viewH)];
        [view addSubview:littleView];
        littleView.tag = i;
        
    
        if(littleView.tag == 0)
        {
            UILabel *titleLabel = [[UILabel alloc]initWithFrame:littleView.bounds];
            titleLabel.textColor = YMColor(239, 128, 179);
            titleLabel.text = @"既往病史调查";
            titleLabel.font = [UIFont systemFontOfSize:18.0f];
            titleLabel.textAlignment = NSTextAlignmentCenter;
            [littleView addSubview:titleLabel];
        }
        if(littleView.tag == 1)
        {
            UILabel *tnbLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 0, w / 4.0, viewH / 2.0)];
            tnbLabel.text = @"糖尿病:";
            tnbLabel.font = [UIFont systemFontOfSize:16.0f];
            tnbLabel.textColor = YMColor(125, 125, 125);
            [littleView addSubview:tnbLabel];
            
            UIButton *noButton = [[UIButton alloc]initWithFrame:CGRectMake(w / 4.0 + 25, (viewH / 2.0 - 20) * 0.5, 20, 20)];
            [noButton setImage:[UIImage imageNamed:@"ssgl_xuanzhong01"] forState:UIControlStateNormal];
            self.noButton = noButton;
            noButton.tag = 1;
            [littleView addSubview:noButton];
            
            UILabel *noLabel = [[UILabel alloc]initWithFrame:CGRectMake(w / 4.0 + 45 + 15, 0, 30, viewH / 2.0)];
            noLabel.textColor = YMColor(125, 125, 125);
            noLabel.text = @"无";
            noLabel.font = [UIFont systemFontOfSize:16.0f];
            [littleView addSubview:noLabel];
            
            UIButton *haveButton = [[UIButton alloc]initWithFrame:CGRectMake(w / 4.0 + 65 + 50, (viewH / 2.0 - 20) * 0.5, 20, 20)];
            [haveButton setImage:[UIImage imageNamed:@"ssgl_xuanzhong02"] forState:UIControlStateNormal];
            self.haveButton = haveButton;
            haveButton.tag = 2;
            [littleView addSubview:haveButton];
            
            UILabel *haveLabel = [[UILabel alloc]initWithFrame:CGRectMake(w / 4.0 + 95 + 55, 0, 30, viewH / 2.0)];
            haveLabel.textColor = YMColor(125, 125, 125);
            haveLabel.text = @"有";
            haveLabel.font = [UIFont systemFontOfSize:16.0f];
            [littleView addSubview:haveLabel];
            
            UILabel *jianceLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, viewH / 2.0 - 5, w, viewH / 2.0)];
            jianceLabel.textColor = YMColor(125, 125, 125);
            jianceLabel.text = @"妊娠糖尿病检测:";
            jianceLabel.font = [UIFont systemFontOfSize:16.0f];
            [littleView addSubview:jianceLabel];
            
            [noButton addTarget:self action:@selector(selectTangNiaoBing:) forControlEvents:UIControlEventTouchUpInside];
            [haveButton addTarget:self action:@selector(selectTangNiaoBing:) forControlEvents:UIControlEventTouchUpInside];
        }
        if(littleView.tag == 2)
        {
            CGFloat lh = viewH / 2.0;
            CGFloat lw = lh * 2.22;
            CGFloat x = (w - lw * 2) / 5.0;
            UIButton *nowButton = [UIButton buttonWithType:UIButtonTypeCustom];
            nowButton.frame = CGRectMake(x * 2, viewH / 4.0, lw, lh);
            nowButton.layer.cornerRadius = 5.0f;
            nowButton.backgroundColor = YMColor(252, 160, 207);
            nowButton.tag = 1;
            [nowButton setTitle:@"马上检测" forState:UIControlStateNormal];
            nowButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
            [nowButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [littleView addSubview:nowButton];
            
            UIButton *laterButton = [UIButton buttonWithType:UIButtonTypeCustom];
            laterButton.frame = CGRectMake(x * 3 + lw, viewH / 4.0, lw, lh);
            laterButton.layer.cornerRadius = 8.0f;
            laterButton.backgroundColor = YMColor(252, 160, 207);
            laterButton.tag = 2;
            [laterButton setTitle:@"下次再测" forState:UIControlStateNormal];
            laterButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
            [laterButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [littleView addSubview:laterButton];
            //点击糖尿病上的两个按钮
            [laterButton addTarget:self action:@selector(clickCloseButton:) forControlEvents:UIControlEventTouchUpInside];
            [nowButton addTarget:self action:@selector(clickCloseButton:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
}

//选择是否有糖尿病
-(void)selectTangNiaoBing:(UIButton *)btn
{
    if(btn.tag == 1)
    {
        [self.noButton setImage:[UIImage imageNamed:@"ssgl_xuanzhong01"] forState:UIControlStateNormal];
        [self.haveButton setImage:[UIImage imageNamed:@"ssgl_xuanzhong02"] forState:UIControlStateNormal];
        self.tnbType = 0;
    }
    else
    {
        [self.noButton setImage:[UIImage imageNamed:@"ssgl_xuanzhong02"] forState:UIControlStateNormal];
        [self.haveButton setImage:[UIImage imageNamed:@"ssgl_xuanzhong01"] forState:UIControlStateNormal];
        self.tnbType = 1;
    }
}
-(void)clickCloseButton:(UIButton *)btn
{
    self.tnbBackgroundView.hidden = YES;
    self.tnbView.hidden = YES;
    //马上检测
    if(btn.tag == 1)
    {
//        YBHealthControllerNew *ybhealth = [[YBHealthControllerNew alloc]init];
////        ybhealth.dayCountInt = self.dayCountInt;
//        [self.navigationController pushViewController:ybhealth animated:YES];
//
//        [passValue passValue].saveDataUserName = self.userName;
//        [passValue passValue].passValueName = [[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"];
    }
    else // 下次再测
    {
        
    }
    [self postTnbInformationToServicesWithTnbType:self.tnbType];
}
/**从服务器上获取糖尿病的信息*/
-(void)getTangNiaoBingInformationfromServices
{
    NSString *urlString = @"http://120.24.178.16:8080/Health/baby/getUserInfo.do";
    NSURL *url = [[NSURL alloc]initWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
    request.HTTPMethod = @"POST";
    NSString *str = [NSString stringWithFormat:@"account=%@&type=2",[[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"]];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data)
        {
            [MBProgressHUD hideHUD];
            // 请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            if([[dict objectForKey:@"data"]isEqualToString:@"0"])
            {
                [self.noButton setImage:[UIImage imageNamed:@"ssgl_xuanzhong01"] forState:UIControlStateNormal];
                [self.haveButton setImage:[UIImage imageNamed:@"ssgl_xuanzhong02"] forState:UIControlStateNormal];
            }
            else
            {
               
                [self.noButton setImage:[UIImage imageNamed:@"ssgl_xuanzhong02"] forState:UIControlStateNormal];
                [self.haveButton setImage:[UIImage imageNamed:@"ssgl_xuanzhong01"] forState:UIControlStateNormal];
            }
        }
    }];
}

/**上传糖尿病病史*/
-(void)postTnbInformationToServicesWithTnbType:(int)tnbType
{
    NSString *urlString = @"http://120.24.178.16:8080/Health/baby/updateUserInfo.do";
    NSURL *url = [[NSURL alloc]initWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
    request.HTTPMethod = @"POST";
    NSString *str = [NSString stringWithFormat:@"account=%@&type=4&info=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"],[NSString stringWithFormat:@"%d",tnbType]];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data)
        {
            [MBProgressHUD hideHUD];
            // 请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//            YMLog(@"dict = %@",dict);
            if([dict[@"code"] isEqualToString:@"0"])
            {
//                [MBProgressHUD showSuccess:@"上传成功!!"];
            }
            else
            {
//                [MBProgressHUD showError:@"上传失败，请重新上传!"];
            }
        }
    }];
}

/**滑动页面布局*/
-(void)scrollViewLayout
{
    self.displayScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, kDeviceWidth, kDeviceHeight)];
    self.displayScrollView.scrollEnabled = NO;
    [self.view addSubview:self.displayScrollView];
    
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kDeviceWidth, kDeviceHeight)];
    view1.tag = 1;
    self.view1 = view1;
    [self.displayScrollView addSubview:view1];
    
    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(0, kDeviceHeight, kDeviceWidth, kDeviceHeight)];
    view2.tag = 2;
    self.view2 = view2;
    [self.displayScrollView addSubview:view2];
    
    [self firstLayout:view1];
    
}


/**第一个页面布局*/
-(void)firstLayout:(UIView *)view
{
    CGFloat w = view.frame.size.width;
    CGFloat y = 0;
    UILabel *timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, w, 40.f)];
    timeLabel.textColor = YMColor(140, 140, 140);
    timeLabel.text = [NSString stringWithFormat:@"您在%@的膳食摄入量",self.selectDateString];
    timeLabel.textAlignment = NSTextAlignmentCenter;
    self.timeLabel = timeLabel;
    [view addSubview:timeLabel];
    
    y += timeLabel.frame.size.height - 5;
    
    UIImageView *goldImageView = [[UIImageView alloc]initWithFrame:CGRectMake((w - w * 0.55) * 0.5, y, w * 0.55, w * 0.55)];
    goldImageView.image = [UIImage imageNamed:@"ssgl_Round"];
    [view addSubview:goldImageView];
    
    UIView *goldView = [[UIView alloc]initWithFrame:goldImageView.frame];
    [view addSubview:goldView];
    
    [self addNeirongToView:goldView andGoldString:@"0"];
    
    //糖尿病按钮
    UIButton *tnbBtn  = [UIButton buttonWithType:UIButtonTypeCustom];
    tnbBtn.frame = CGRectMake(w - (w - w * 0.55) * 0.5 - 5, y + 5, 80, 60);
    [view addSubview:tnbBtn];
    
    [tnbBtn setImage:[UIImage imageNamed:@"ssgl_糖尿病icon"] forState:UIControlStateNormal];
    tnbBtn.imageEdgeInsets = UIEdgeInsetsMake(5, 22, 19, 22);
    [tnbBtn setTitle:@"糖尿病调查" forState:UIControlStateNormal];
    tnbBtn.titleEdgeInsets = UIEdgeInsetsMake(33, -50, 0, 0);
    [tnbBtn setTitleColor:YMColor(172, 172, 172) forState:UIControlStateNormal];
    tnbBtn.titleLabel.font = [UIFont systemFontOfSize:13.0];
    
    [tnbBtn addTarget:self action:@selector(clickTnbButton) forControlEvents:UIControlEventTouchUpInside];
    
    y += goldImageView.frame.size.height + 5;
    
    UIView *buttonView = [[UIView alloc]initWithFrame:CGRectMake(0, y, kDeviceWidth, kDeviceHeight / 9.47)];
    [view addSubview:buttonView];
    [self addButtonToView:buttonView];
    
    y += buttonView.frame.size.height;
    UILabel *jiegouLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, y, kDeviceWidth, kDeviceHeight / 16.23)];
    jiegouLabel.backgroundColor = [UIColor whiteColor];
    jiegouLabel.text = @"      今日膳食结构";
    jiegouLabel.textColor = YMColor(193, 88, 142);
    [view addSubview:jiegouLabel];
    
    y += jiegouLabel.frame.size.height;
    UILabel *crossLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, y, w, 1)];
    crossLabel.backgroundColor = YMColor(224, 224, 224);
    [view addSubview:crossLabel];
    
    y += crossLabel.frame.size.height;

    //膳食结构下的线条
    CGFloat foodW = kDeviceWidth / 4.0;
    CGFloat foodH = (kDeviceHeight - y - 100) * 0.5;
    
    int tag = 0;
    for(int j = 0;j < 2;j ++)
    {
        for(int i = 0;i < 4;i ++)
        {
            foodJieGouView *foodJieGou = [[foodJieGouView alloc]initWithFrame:CGRectMake(foodW * i,y + foodH * j, foodW, foodH)];
            [view addSubview:foodJieGou];
            foodJieGou.tag = tag ++;
           

            [foodJieGou setViewTitle:self.titleArray[tag - 1] andTotallabel:self.totalMutableArray[tag - 1] andSheruCount:self.alreadyMutableArray[tag - 1]];
        }
    }
    for(int i = 0;i < 4;i ++)
    {
        UILabel *shulabel = [[UILabel alloc]initWithFrame:CGRectMake(foodW * i, y, 1, foodH * 2)];
        shulabel.backgroundColor = YMColor(224, 224, 224);
        [view addSubview:shulabel];
    }
    for(int i = 0;i < 2;i ++)
    {
        UILabel *crossLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, y + foodH * (i + 1), kDeviceWidth ,1)];
        crossLabel.backgroundColor = YMColor(224, 224, 224);
        [view addSubview:crossLabel];
    }

        y = kDeviceHeight - 35 - 64;
    [self setButtonShuxingY:y andW:w andimageName:@"ssgl_arrowDOWN01" ToView:view andLabelH:17.0f];
}

//点击糖尿病按钮
-(void)clickTnbButton
{
    self.tnbBackgroundView.hidden = NO;
    self.tnbView.hidden = NO;
}

//上拉和下滑按钮
-(void)setButtonShuxingY:(CGFloat)y andW:(CGFloat)w andimageName:(NSString *)imageName ToView:(UIView *)view andLabelH:(CGFloat)h
{
    UILabel *pickLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, y + h, kDeviceWidth, 18)];
    pickLabel.backgroundColor = YMColor(254, 233, 244);
    [view addSubview:pickLabel];
    
    UIButton *xialaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    xialaButton.frame = CGRectMake(kDeviceWidth / 2.0 - 35, y, 70,35);
    [xialaButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [view addSubview:xialaButton];
    xialaButton.tag = view.tag;
    [xialaButton addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
}

/**第二个页面布局*/
-(void)secondLayout:(UIView *)view
{
    CGFloat h = view.frame.size.height;
    CGFloat w = view.frame.size.width;
    CGFloat y = 0.0f;
    [self setButtonShuxingY:y andW:w andimageName:@"ssgl_arrowUP01" ToView:view andLabelH:0.f];
    y += 36.0f;
    
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, y, w, h - y)];
    [view addSubview:scrollView];
    // 去掉弹簧效果
    scrollView.bounces = NO;
    self.secY = 0;
    
    UILabel *shansiPlanlabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.secY, w, 40.0f)];
    shansiPlanlabel.backgroundColor = [UIColor whiteColor];
    shansiPlanlabel.text = @"      膳食计划";
    shansiPlanlabel.textColor = YMColor(193, 88, 142);
    [scrollView addSubview:shansiPlanlabel];
    
    CGFloat sw = shansiPlanlabel.frame.size.width;
    CGFloat sh = shansiPlanlabel.frame.size.height;
    UIButton *changePlanbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    changePlanbtn.frame = CGRectMake(sw - 120, self.secY, 100, sh);
    [changePlanbtn setImage:[UIImage imageNamed:@"assistant_》gray"] forState:UIControlStateNormal];
    [changePlanbtn setTitle:@"修改计划" forState:UIControlStateNormal];
    [changePlanbtn setTitleColor:YMColor(157, 157, 157) forState:UIControlStateNormal];
    changePlanbtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [scrollView addSubview:changePlanbtn];
    changePlanbtn.imageEdgeInsets = UIEdgeInsetsMake(sh / 3.0, 100 - sh / 3.0 - 15, sh / 3.0, 15);
    changePlanbtn.titleEdgeInsets = UIEdgeInsetsMake(0, -40, 0, sh / 3.0);
    [changePlanbtn addTarget:self action:@selector(clickChangeButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.secY += shansiPlanlabel.frame.size.height;
    UILabel *crossLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.secY, kDeviceWidth, 1)];
    crossLabel.backgroundColor = YMColor(224, 224, 224);
    [scrollView addSubview:crossLabel];
    self.secY += crossLabel.frame.size.height;
    
    [self kindOfCanLayoutToScrollView:scrollView andY:self.secY andTitleString:@"      早餐（06:30～08:30）"];
    [self chuanjianFoodList:(int)self.breakFastArray.count toScrollView:scrollView andArray:self.breakFastArray];
    [self kindOfCanLayoutToScrollView:scrollView andY:self.secY andTitleString:@"      早加餐"];
    [self chuanjianFoodList:(int)self.breakFastPlusArray.count toScrollView:scrollView andArray:self.breakFastPlusArray];
    [self kindOfCanLayoutToScrollView:scrollView andY:self.secY andTitleString:@"      午餐（11:30～12:30）"];
    [self chuanjianFoodList:(int)self.lunchFastArray.count toScrollView:scrollView andArray:self.lunchFastArray];
    [self kindOfCanLayoutToScrollView:scrollView andY:self.secY andTitleString:@"      午加餐"];
    [self chuanjianFoodList:(int)self.lunchFastPlusArray.count toScrollView:scrollView andArray:self.lunchFastPlusArray];
    [self kindOfCanLayoutToScrollView:scrollView andY:self.secY andTitleString:@"      晚餐（17:30～18:30）"];
    [self chuanjianFoodList:(int)self.dinnerFastArray.count toScrollView:scrollView andArray:self.dinnerFastArray];
    [self kindOfCanLayoutToScrollView:scrollView andY:self.secY andTitleString:@"      晚加餐"];
    [self chuanjianFoodList:(int)self.dinnerFastPlusArray.count toScrollView:scrollView andArray:self.dinnerFastPlusArray];
    
    UILabel *lastCrossLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.secY, kDeviceWidth, 1)];
    lastCrossLabel.backgroundColor = YMColor(224, 224, 224);
    [scrollView addSubview:lastCrossLabel];

    self.secY += 30;
   //复制到膳食记录按钮
    UIButton *copyButton = [UIButton buttonWithType:UIButtonTypeCustom];
    copyButton.frame = CGRectMake(kDeviceWidth * 0.25, self.secY, kDeviceWidth * 0.5, kDeviceWidth * 0.5 / 3.8);
    copyButton.layer.cornerRadius = 10.0;
    copyButton.backgroundColor = YMColor(252, 160, 207);
    [copyButton setTitle:@"复制到膳食记录" forState:UIControlStateNormal];
    [copyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [scrollView addSubview:copyButton];
    
    [copyButton addTarget:self action:@selector(clickCopyButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.secY += copyButton.frame.size.height + 30;
//    UIButton *noPlanButton = [[UIButton alloc]initWithFrame:CGRectMake(kDeviceWidth * 0.25, self.secY, kDeviceWidth * 0.5, 40)];
//    [noPlanButton setTitleColor:YMColor(252, 166, 210) forState:UIControlStateNormal];
//    [noPlanButton setTitle:@"还没计划，去记录吧" forState:UIControlStateNormal];
//    [noPlanButton setImage:[UIImage imageNamed:@"personal_》small"] forState:UIControlStateNormal];
//    noPlanButton.imageEdgeInsets = UIEdgeInsetsMake(10, kDeviceWidth * 0.5 - 23, 10, 3);
//    noPlanButton.titleLabel.font = [UIFont systemFontOfSize:16.0f];
//    noPlanButton.titleEdgeInsets = UIEdgeInsetsMake(0, -37, 0, 20);
//    [scrollView addSubview:noPlanButton];
//    self.secY += noPlanButton.frame.size.height;
    
    //红色横条
    UILabel *pinkLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.secY + 32, kDeviceWidth, 18)];
    pinkLabel.backgroundColor = YMColor(254, 206, 230);
    [scrollView addSubview:pinkLabel];
    scrollView.contentSize = CGSizeMake(kDeviceWidth, self.secY + 114);
    
    
   
}

/**创建各餐的食物列表*/
-(void)chuanjianFoodList:(int)count toScrollView:(UIScrollView *)scrollView andArray:(NSArray *)Foodarray;
{
   
    for(int i = 0;i < count;i ++)
    {
        // loadNibNamed 会将名为AppInfoView中定义的所有视图全部加载出来，并且按照XIB中定义的顺序，返回一个视图的数组
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"foodPlanView" owner:nil options:nil];
        foodPlanView *foodView = [array firstObject];
        foodView.frame = CGRectMake(0,self.secY,kDeviceWidth,kDeviceHeight / 8.1);
        foodView.backgroundColor = YMColor(245, 245, 245);
        [scrollView addSubview:foodView];
    
        foodPlan *fff = Foodarray[i];
        foodView.foodName.text = [NSString stringWithFormat:@"%@", fff.foodName];
        foodView.foodWeight.text = [NSString stringWithFormat:@"%dg", [fff.foodWeight intValue]];
        
        NSURL *url = [NSURL URLWithString:fff.foodPic];
        [foodView.foodImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"zonghe"]];
        foodView.changeButton.layer.cornerRadius = 8.0;
        foodView.changeButton.layer.borderWidth = 1.0;
        foodView.changeButton.layer.borderColor = [YMColor(250, 193, 220)CGColor];
        foodView.changeButton.tag = [fff.foodID integerValue];
        [foodView.changeButton addTarget:self action:@selector(clickExchangeButton:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.foodMutableArrayM addObject:fff];
        
        self.secY += foodView.frame.size.height;
        if(i != count - 1)
        {
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, self.secY, kDeviceWidth, 1)];
            label.backgroundColor = YMColor(224, 224, 224);
            [scrollView addSubview:label];
            self.secY += 1;
        }
    }
  
}


/**从网上下载食物图片*/
-(UIImage *)downimageFromInternet:(NSString *)str
{
    NSURL *url = [NSURL URLWithString:str];
    NSData *resultData1 = [NSData dataWithContentsOfURL:url];
    UIImage *img1 = [UIImage imageWithData:resultData1];
    return img1;
}
//早餐，早加餐，中餐，中加餐，晚餐，晚加餐统一布局
-(void)kindOfCanLayoutToScrollView:(UIScrollView *)scrollView andY:(CGFloat)y andTitleString:(NSString *)titleString
{
    UILabel *canLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, y, kDeviceWidth, 40.f)];
    canLabel.text = titleString;
    canLabel.textColor = YMColor(191, 87, 141);
    canLabel.backgroundColor = YMColor(254, 233, 244);
    [scrollView addSubview:canLabel];
    self.secY += canLabel.frame.size.height;
}

//点击了食物交换按钮
-(void)clickExchangeButton:(UIButton *)btn
{
    [passValue passValue].exchangeFoodFlag = NO;
    foodExchangeViewController *exchange = [[foodExchangeViewController alloc]init];
    [self.navigationController pushViewController:exchange animated:YES];
    for (foodPlan *fff in self.foodMutableArrayM) {
        if([fff.foodID intValue] == (int)btn.tag)
        {
            exchange.foodType = fff.foodType;
            exchange.foodID = fff.foodID;
            exchange.foodCode = fff.foodCode;
            exchange.foodWeight = fff.foodWeight;
        }
    }
}

//点击修改计划按钮
-(void)clickChangeButton
{
    planFoodViewController *plan = [[planFoodViewController alloc]init];
    [self.navigationController pushViewController:plan animated:YES];
}

//往图片上添加文字
-(void)addNeirongToView:(UIView *)view andGoldString:(NSString *)goldString
{
    CGFloat w = view.frame.size.width;
    CGFloat h = view.frame.size.height * 0.75;
    CGFloat y = view.frame.size.height * 0.125;
    
    UILabel *firLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, y + 15, w, h / 3.0)];
    firLabel.text = @"今天还可以摄入";
    firLabel.textColor = YMColor(101, 101, 101);
    firLabel.textAlignment = NSTextAlignmentCenter;
    firLabel.font = [UIFont systemFontOfSize:13.0f];
    self.firstLabel = firLabel;
    [view addSubview:firLabel];
    
    y += firLabel.frame.size.height;
    
    UILabel *secLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, y, w, h / 3.0)];
    secLabel.textAlignment = NSTextAlignmentCenter;
    secLabel.textColor = YMColor(28, 193, 147);
    secLabel.text = goldString;
    secLabel.font = [UIFont systemFontOfSize:30.0];
    self.goldLabel = secLabel;
    [view addSubview:secLabel];
    
    y += secLabel.frame.size.height;
    
    UILabel *thiLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, y - 12, w, h / 3.0)];
    thiLabel.textColor = YMColor(101, 101, 101);
    thiLabel.textAlignment = NSTextAlignmentCenter;
    thiLabel.text = @"千卡";
    thiLabel.font = [UIFont systemFontOfSize:13.0f];
    [view addSubview:thiLabel];
}

/**往view上添加膳食原则，膳食纪录，膳食分析按钮*/
-(void)addButtonToView:(UIView *)view
{
    CGFloat h = view.frame.size.height;
    CGFloat w = view.frame.size.width - 60;
    for(int i = 0;i < 3;i ++)
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(15 * (i + 1) + w / 3.0 * i, 0, w / 3.0, h);
        btn.tag = i + 1;
        [view addSubview:btn];
        
        btn.imageEdgeInsets = UIEdgeInsetsMake(8, (w / 3.0 - 30) * 0.5, h - 38, (w / 3.0 - 30) * 0.5);
        btn.titleEdgeInsets = UIEdgeInsetsMake(38, - w / 3.0 + w / 5.45, 0, 0);
        btn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        [btn setTitleColor:YMColor(174, 174, 174) forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(selectGongnengButton:) forControlEvents:UIControlEventTouchUpInside];
        
        switch (btn.tag) {
            case 1:
                [btn setImage:[UIImage imageNamed:@"ssgl_原则icon"] forState:UIControlStateNormal];
                [btn setTitle:@"膳食原则" forState:UIControlStateNormal];
                break;
            case 2:
                [btn setImage:[UIImage imageNamed:@"ssgl_记录icon"] forState:UIControlStateNormal];
                [btn setTitle:@"膳食记录" forState:UIControlStateNormal];
                break;
            case 3:
                [btn setImage:[UIImage imageNamed:@"ssgl_分析icon"] forState:UIControlStateNormal];
                [btn setTitle:@"膳食分析" forState:UIControlStateNormal];
                break;
            default:
                break;
        }
    }
    UILabel *crossLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, h - 1, w, 1)];
    crossLabel.backgroundColor = YMColor(224, 224, 224);
    [view addSubview:crossLabel];
}

/**选择膳食原则，膳食记录，膳食分析功能按钮*/
-(void)selectGongnengButton:(UIButton *)btn
{
    //膳食原则
    if(btn.tag == 1)
    {
        foodYuanzeViewController *yuanze = [[foodYuanzeViewController alloc]init];
        [self.navigationController pushViewController:yuanze animated:YES];
    }
    //膳食记录
    if(btn.tag == 2)
    {
        foodJiluViewController *foodJilu = [[foodJiluViewController alloc]init];
        [self.navigationController pushViewController:foodJilu animated:YES];
        foodJilu.selectDateString = self.selectDateString;
    }
    //膳食分析
    if(btn.tag == 3)
    {
        shanshiFenxiViewController *fenxi = [[shanshiFenxiViewController alloc]init];
        [self.navigationController pushViewController:fenxi animated:YES];
        fenxi.selectDateString = self.selectDateString;
    }
}

-(void)clickButton:(UIButton *)btn
{
    
    if(btn.tag == 1)
    {
        [UIView animateWithDuration:0.5 animations:^{
            self.displayScrollView.contentOffset = CGPointMake(0, kDeviceHeight);
        }];
    }
    else
    {
//          [self getPlanInformationFromServices];
        [UIView animateWithDuration:0.5 animations:^{
            self.displayScrollView.contentOffset = CGPointMake(0, 0);
        }];
    }
}

//获取系统时间
-(NSString *)getSystemTime
{
    NSDate *senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    return locationString;
}

/**从服务器获取膳食结构的内容*/
-(void)getFoodInformationFromServices
{
    [MBProgressHUD showMessage:@"正在拼命加载中，请稍后..."];
    NSString *urlString = @"http://120.24.178.16:8080/Health/food/findUserfoodRecordByDay.do";
    NSURL *url = [[NSURL alloc]initWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
    request.HTTPMethod = @"POST";
    NSString *str = [NSString stringWithFormat:@"Account=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"]];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data)
        {
            [MBProgressHUD hideHUD];
            // 请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//            YMLog(@"dict = %@",dict );
            NSDictionary *dataDic = [dict objectForKey:@"data"]; //总的份数
            NSArray *dataArray = [dict objectForKey:@"data1"]; //已经摄入的份数
            NSDictionary *dataDic2 = [dict objectForKey:@"data2"];//还剩多少卡路里可以摄入
            NSString *eatEnergy = [NSString stringWithFormat:@"%@",[dict objectForKey:@"eatEnergy"]];
            
            self.alreadyMutableArray = (NSMutableArray *)dataArray;
            [self.totalMutableArray addObject:[dataDic objectForKey:@"rice"]];//谷薯
            [self.totalMutableArray addObject:[dataDic objectForKey:@"vegetable"]];//蔬菜
            [self.totalMutableArray addObject:[dataDic objectForKey:@"fruit"]];//水果
            [self.totalMutableArray addObject:[dataDic objectForKey:@"bean"]];//大豆
            [self.totalMutableArray addObject:[dataDic objectForKey:@"milk"]];//奶类
            [self.totalMutableArray addObject:[dataDic objectForKey:@"meat"]];//肉蛋
            [self.totalMutableArray addObject:[dataDic objectForKey:@"nut"]];//硬果
            [self.totalMutableArray addObject:[dataDic objectForKey:@"fat"]];//油脂
         
            [self scrollViewLayout];
            
            int sheyuInt = 0;
            if([[dataDic2 objectForKey:@"energy"]intValue] >= [eatEnergy intValue])
            {
                sheyuInt = [[dataDic2 objectForKey:@"energy"]intValue] - [eatEnergy intValue];
                self.firstLabel.textColor = YMColor(101, 101, 101);
                
            }
            else
            {
                sheyuInt = [eatEnergy intValue] - [[dataDic2 objectForKey:@"energy"]intValue];
                self.firstLabel.text = @"今天摄入已超出";
                self.firstLabel.textColor = [UIColor redColor];
            }
            self.goldLabel.text = [NSString stringWithFormat:@"%d",sheyuInt];
//            [self getPlanInformationFromServices];
            [self tangniaobingLayout];
             [self getPlanInformationFromServices];
        }
    }];
}

/**从服务器上获取膳食计划的内容*/
-(void)getPlanInformationFromServices
{
//    [MBProgressHUD showMessage:@"正在拼命加载中，请稍后..."];
    NSString *urlString = @"http://120.24.178.16:8080/Health/food/findFoodByDay.do";
    NSURL *url = [[NSURL alloc]initWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
    request.HTTPMethod = @"POST";
    NSString *str = [NSString stringWithFormat:@"&userName=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"]];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data)
        {
            [MBProgressHUD hideHUD];
            // 请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//            YMLog(@"dict = %@",dict);
            NSDictionary *dataDic = [dict objectForKey:@"data"];
            NSArray *foodDayTimes = [dataDic objectForKey:@"foodDayTimes"];
            for (NSDictionary *foodItems in foodDayTimes) {
                    if([[foodItems objectForKey:@"foodTime"]intValue] == 0)
                    {
                        for (NSDictionary *qqq in [foodItems objectForKey:@"foodItems"]) {
                           foodPlan *fff = [foodPlan foodInfoWithDict:qqq];
                            [self.breakFastArray addObject:fff];
                            
                        }
                        
                    }
                    if([[foodItems objectForKey:@"foodTime"] intValue ] == 1)
                    {
                        for (NSDictionary *qqq in [foodItems objectForKey:@"foodItems"]) {
                            foodPlan *fff = [foodPlan foodInfoWithDict:qqq];
                            [self.breakFastPlusArray addObject:fff];
                            
                        }
                    }
                    if([[foodItems objectForKey:@"foodTime"] intValue ] == 2)
                    {
                        for (NSDictionary *qqq in [foodItems objectForKey:@"foodItems"]) {
                            foodPlan *fff = [foodPlan foodInfoWithDict:qqq];
                            [self.lunchFastArray addObject:fff];
                           
                        }
                    }
                    if([[foodItems objectForKey:@"foodTime"] intValue ] == 3)
                    {
                        for (NSDictionary *qqq in [foodItems objectForKey:@"foodItems"]) {
                           foodPlan *fff = [foodPlan foodInfoWithDict:qqq];
                            [self.lunchFastPlusArray addObject:fff];
                         
                        }
                    }
                    if([[foodItems objectForKey:@"foodTime"] intValue ] == 4)
                    {
                        for (NSDictionary *qqq in [foodItems objectForKey:@"foodItems"]) {
                           foodPlan *fff = [foodPlan foodInfoWithDict:qqq];
                            [self.dinnerFastArray addObject:fff];
                            
                        }
                    }
                    if([[foodItems objectForKey:@"foodTime"] intValue ] == 5)
                    {
                        for (NSDictionary *qqq in [foodItems objectForKey:@"foodItems"]) {
                            foodPlan *fff = [foodPlan foodInfoWithDict:qqq];
                            [self.dinnerFastPlusArray addObject:fff];
                            
                        }
                    }
            }
            [self secondLayout:self.view2];
            
                    }
    }];
}


/**点击了复制到膳食记录的按钮*/
-(void)clickCopyButton
{
    NSString *urlString = @"http://120.24.178.16:8080/Health/food/copyFoodRecord.do";
    NSURL *url = [[NSURL alloc]initWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
    request.HTTPMethod = @"POST";
    NSString *str = [NSString stringWithFormat:@"userName=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"]];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data)
        {
            [MBProgressHUD hideHUD];
            // 请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//            YMLog(@"dict = %@",dict );
            if([[dict objectForKey:@"code"] isEqualToString:@"0"])
            {
                [MBProgressHUD showSuccess:@"复制成功!!"];
                [[NSUserDefaults standardUserDefaults]setObject:@"haveChanged" forKey:@"changed"];
                for (UIView *view in self.view1.subviews) {
                    [view removeFromSuperview];
                }
                [UIView animateWithDuration:0.5 animations:^{
                    self.displayScrollView.contentOffset = CGPointMake(0, 0);
                    self.foodMutableArrayM = [NSMutableArray array];
                    self.breakFastArray = [NSMutableArray array];
                    self.breakFastPlusArray = [NSMutableArray array];
                    self.lunchFastArray = [NSMutableArray array];
                    self.lunchFastPlusArray = [NSMutableArray array];
                    self.dinnerFastArray = [NSMutableArray array];
                    self.dinnerFastPlusArray = [NSMutableArray array];
                    [self getFoodInformationFromServices];
                }];
                
            }
            else
            {
                [MBProgressHUD showError:[dict objectForKey:@"message"]];
            }
        }
    }];

}

@end
